package com.plian.system.service.pm.propertychange;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.cache.PropertyCache;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.baseinfo.ValueSetConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dao.bt.baseinfo.BaseInfoDao;
import com.plian.system.dao.pm.contributor.ContributorBasicsDao;
import com.plian.system.dao.pm.contributor.ContributorDao;
import com.plian.system.dao.pm.contributor.ContributorRecordDao;
import com.plian.system.dao.pm.contributorchange.ContributorChangeDao;
import com.plian.system.dao.pm.partneroutbound.PartnerOutboundBasicsDao;
import com.plian.system.dao.pm.partneroutbound.PartnerOutboundChangeDao;
import com.plian.system.dao.pm.partneroutbound.PartnerOutboundRecordDao;
import com.plian.system.dao.pm.partnersituation.PartnerSituationBascicsDao;
import com.plian.system.dao.pm.partnersituation.PartnerSituationChangeDao;
import com.plian.system.dao.pm.partnersituation.PartnerSituationRecordDao;
import com.plian.system.dao.pm.property.PropertyBasicsDao;
import com.plian.system.dao.pm.property.PropertyDao;
import com.plian.system.dao.pm.property.PropertyRecordDao;
import com.plian.system.dao.pm.propertychange.PropertyChangeDao;
import com.plian.system.dao.pm.propertyout.PropertyOutDao;
import com.plian.system.dao.pm.shareholding.ShareholdingBasicsDao;
import com.plian.system.dao.pm.shareholding.ShareholdingChangeDao;
import com.plian.system.dao.pm.shareholding.ShareholdingRecordDao;
import com.plian.system.dao.sys.file.FileDao;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.dto.pm.property.PropertyChangeDTO;
import com.plian.system.entity.pm.property.PropertyBasics;
import com.plian.system.entity.sys.ApprovalMessage;
import com.plian.system.excel.ExcelExportUtil;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.model.page.Page;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.service.bt.baseinfo.BaseInfoService;
import com.plian.system.service.pm.property.IPropertyBasicsService;
import com.plian.system.service.pm.property.helper.PropertyChangeHelper;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.OrgzationService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pm.property.EconomicBehaviorCountVO;
import com.plian.system.vo.report.HeaderVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.vo.report.ReportVO;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.poi.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.KT_TYPE;
import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.PROPERTY_CHANGE;
import static com.plian.system.constant.sys.FormStatusConstant.*;
import static com.plian.system.constant.sys.FormTypeConstant.PM_PROPERTYCHANGE_FORM;

/**
 * 产权变动
 */
@Service
public class  PropertyChangeService implements BaseFlowService {
    private static final Logger log = LoggerFactory.getLogger(PropertyChangeService.class);
    @Autowired
    PropertyChangeDao propertyChangeDao;
    @Autowired
    ContributorChangeDao contributorChangeDao;
    @Autowired
    PropertyDao propertyDao;
    @Autowired
    PropertyBasicsDao propertyBasicsDao;
    @Autowired
    OrgzationDao orgzationDao;
    @Autowired
    FileService fileService;
    @Autowired
    BaseInfoDao baseInfoDao;
    @Autowired
    private FormWorkflowService formWorkflowService;
    @Autowired
    ContributorDao contributorDao;
    @Autowired
    ShareholdingChangeDao shareholdingChangeDao;
    @Autowired
    PartnerSituationChangeDao partnerSituationChangeDao;
    @Autowired
    PartnerOutboundChangeDao partnerOutboundChangeDao;
    @Autowired
    PropertyRecordDao propertyRecordDao;
    @Autowired
    ContributorBasicsDao contributorBasicsDao;
    @Autowired
    ShareholdingBasicsDao shareholdingBasicsDao;
    @Autowired
    PartnerSituationBascicsDao partnerSituationBascicsDao;
    @Autowired
    PartnerOutboundBasicsDao partnerOutboundBasicsDao;
    @Autowired
    ContributorRecordDao contributorRecordDao;
    @Autowired
    ShareholdingRecordDao shareholdingRecordDao;
    @Autowired
    PartnerSituationRecordDao partnerSituationRecordDao;
    @Autowired
    PartnerOutboundRecordDao partnerOutboundRecordDao;
    @Autowired
    FileDao fileDao;
    @Autowired
    private BaseInfoService baseInfoService;
    @Autowired
    private PropertyOutDao propertyOutDao;
    @Autowired
    private OrgzationService orgzationService;
    @Autowired
    private IPropertyBasicsService propertyBasicsService;

    @Autowired
    private IApprovalMessageService approvalMessageService;

//    @Autowired TODO DEL
//    private IChangeAssociationService changeAssociationService;

    @Autowired
    private PropertyChangeHelper propertyChangeHelper;

    @Transactional(rollbackFor = RuntimeException.class)
    public ObjResult save(PageData pd) {
        ObjResult objResult;
        try {
            //主表主键
            String pro_id = UuidUtil.get32UUID();
            //变动的资本情况
            objResult = new ObjResult(CommonCode.SUCCESS);
            //主表
            pd.put("id", pro_id);
            pd.put("status", "0");
            pd.put("createUser", TokenUtil.getTokenUserId());
            pd.put("createTime", new Date());
            pd.put("updateUser", TokenUtil.getTokenUserId());
            pd.put("updateTime", new Date());
            pd.put("formType", FormTypeConstant.PM_PROPERTYCHANGE_FORM);
            pd.put("fillOrgId", TokenUtil.getTokenOrgId());
            //匹配组织树
            PageData org = orgzationService.findByName(pd.getString("orgName"), TokenUtil.getCompetentOrganization());
            if (org != null && org.size() > 0) {
                pd.put("orgId", org.getString("id"));
            }

            List<String> majorIndustries_list = (List<String>) pd.get("majorIndustries");
            String majorIndustries = "";
            if (majorIndustries_list != null && majorIndustries_list.size() > 0) {
                majorIndustries = StringUtil.join(majorIndustries_list.toArray(), ",");
            }
            pd.put("majorIndustries", majorIndustries);

            //变动原因
            List<String> changeReason_list = (List<String>) pd.get("changeReason");
            String changeReason = "";
            if (changeReason_list != null && changeReason_list.size() > 0) {
                changeReason = StringUtil.join(changeReason_list.toArray(), ",");
            }
            pd.put("changeReason", changeReason);
            //保存主表
            propertyChangeDao.save(pd);

            //出资人情况
            List<HashMap> list_con = (List<HashMap>) pd.get("list_con");
            ObjectMapper mapper = new ObjectMapper();
            List<PageData> listCon = mapper.convertValue(list_con, new TypeReference<List<PageData>>() {
            });
            if (list_con != null && list_con.size() > 0) {
                //出资人情况
                saveCon(listCon, pro_id);
            }

            //境外控股人
            if ("1".equals(pd.getString("nature"))) {
                //出资人情况
                List<PageData> list_share = (List<PageData>) pd.get("list_share");
                List<PageData> listShare = mapper.convertValue(list_share, new TypeReference<List<PageData>>() {
                });
                if (listCon != null && listCon.size() > 0) {
                    saveShare(listShare, pro_id);
                }
            }

            //合伙人
            if ("2".equals(pd.getString("nature"))) {
                //保存从表: 合伙人登记-情况
                List<PageData> list_PartnerSituation = mapper.convertValue(pd.get("listPartnerSituation"), new TypeReference<List<PageData>>() {});
                savePartnerSituation(list_PartnerSituation, pro_id);
                //保存从表: 对外投资情况
                List<PageData> list_PartnerOutbound = mapper.convertValue(pd.get("listPartnerOutbound"), new TypeReference<List<PageData>>() {});
                savePartnerOutbound(list_PartnerOutbound, pro_id);
            }
            fileSave(pd, pro_id);
            HashMap<String, Object> processVariable = new HashMap<>();
            formWorkflowService.startProcessAndSimulate(pd.getString("id"), pd.getString("formType"), processVariable);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
        return objResult;
    }

    /**
     * 附件处理
     *
     * @param pd
     */
    private void fileSave(PageData pd, String id) {
        List<HashMap> list = new ArrayList<>();
        for (int i = 1; i <= 9; i++) {
            List<HashMap> l = (List<HashMap>) pd.get("f" + i);
            if (l != null && l.size() > 0) {
                for (HashMap hashMap : l) {
                    hashMap.put("type", "f" + i);
                    hashMap.put("id", UuidUtil.get32UUID());
                    list.add(hashMap);
                }
            }
        }
        //保存附件
        fileService.saveAll(id, list);
    }

    /**
     * 附件处理
     *
     * @param pd
     */
    private void fileEdit(PageData pd, String id) {
        List<HashMap> list = new ArrayList<>();
        for (int i = 1; i <= 9; i++) {
            List<HashMap> l = (List<HashMap>) pd.get("f" + i);
            if (l != null && l.size() > 0) {
                for (HashMap hashMap : l) {
                    hashMap.put("type", "f" + i);
                    list.add(hashMap);
                }
            }
        }
        //修改附件
        fileService.edit(id, list);
    }


    @Transactional(rollbackFor = RuntimeException.class)
    public ObjResult edit(PageData pd) {
        ObjResult objResult;
        try {
            List<String> majorIndustries_list = (List<String>) pd.get("majorIndustries");
            String majorIndustries = "";
            if (majorIndustries_list != null && majorIndustries_list.size() > 0) {
                majorIndustries = StringUtil.join(majorIndustries_list.toArray(), ",");
            }

            //变动原因
            List<String> changeReason_list = (List<String>) pd.get("changeReason");
            String changeReason = "";
            if (changeReason_list != null && changeReason_list.size() > 0) {
                changeReason = StringUtil.join(changeReason_list.toArray(), ",");
            }
            pd.put("changeReason", changeReason);
            pd.put("updateTime", new Date());
            pd.put("updateUser", TokenUtil.getTokenUserId());
            pd.put("majorIndustries", majorIndustries);
            String pro_id = pd.getString("id");
            propertyChangeDao.edit(pd);


            List<HashMap> list_con = (List<HashMap>) pd.get("list_con");
            ObjectMapper mapper = new ObjectMapper();
            List<PageData> listCon = mapper.convertValue(list_con, new TypeReference<List<PageData>>() {
            });

            contributorChangeDao.del_parentId(pro_id);
            if (list_con != null && list_con.size() > 0) {
                //出资人情况
                saveCon(listCon, pro_id);
            }

            //境外控股人
            if ("1".equals(pd.getString("nature"))) {
                //出资人情况
                List<PageData> list_share = (List<PageData>) pd.get("list_share");
                List<PageData> listShare = mapper.convertValue(list_share, new TypeReference<List<PageData>>() {
                });
                shareholdingChangeDao.del_parentId(pro_id);
                if (listCon != null && listCon.size() > 0) {
                    saveShare(listShare, pro_id);
                }
            }

            //合伙人
            if ("2".equals(pd.getString("nature"))) {
                //修改从表: 合伙人登记-情况
                List<PageData> list_PartnerSituation = mapper.convertValue(pd.get("listPartnerSituation"), new TypeReference<List<PageData>>() {
                });
                partnerSituationChangeDao.delPrenteId(pro_id);
                savePartnerSituation(list_PartnerSituation, pro_id);
                //修改从表: 对外投资情况
                List<PageData> list_PartnerOutbound = mapper.convertValue(pd.get("listPartnerOutbound"), new TypeReference<List<PageData>>() {
                });
                partnerOutboundChangeDao.delPrenteId(pro_id);
                savePartnerOutbound(list_PartnerOutbound, pro_id);
            }
            fileEdit(pd, pro_id);
            objResult = new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
        return objResult;
    }

    public ObjResult findbyid(PageData pd) {
        ObjResult objResult;
        String pro_id = pd.getString("id");
        try {
            PageData p = propertyChangeDao.findbyid(pro_id);
            p.put("netWorkingName", netWorkingName(p.getString("netWorking")));
            objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
        }
        return objResult;
    }

    private String netWorkingName(String netWorking){
        Map<String, String> netWorkingMap = baseInfoService.getChildMap(ValueSetConstant.NET_WORKING_TYPE);
        if (com.plian.Tools.StringUtil.isNotBlank(netWorking) && netWorkingMap.containsKey(netWorking)) {
            return netWorkingMap.get(netWorking);
        }
        return "";
    }
    /**
     * 保存
     *
     * @param list    从表列表
     * @param prentId 主键id
     */
    private void savePartnerOutbound(List<PageData> list, String prentId) throws Exception {
        if (list != null && list.size() > 0) {
            for (PageData pageData : list) {
                pageData.put("propertyId", prentId);
                pageData.put("id", UuidUtil.get32UUID());
                List<String> industry_list = (List<String>) pageData.get("industry");
                pageData.put("industry", "");
                if (industry_list != null && industry_list.size() > 0) {
                    String industry = StringUtil.join(industry_list.toArray(), ",");
                    pageData.put("industry", industry);
                }

            }
            partnerOutboundChangeDao.saveAll(list);
        }
    }

    /**
     * 保存
     *
     * @param list    从表列表
     * @param prentId 主键id
     */
    private void savePartnerSituation(List<PageData> list, String prentId) throws Exception {
        if (list != null && list.size() > 0) {
            for (PageData pageData : list) {
                pageData.put("propertyId", prentId);
                pageData.put("id", UuidUtil.get32UUID());
            }
            partnerSituationChangeDao.saveAll(list);
        }
    }


    /**
     * 保存境外控股人
     *
     * @param list_share
     * @param pro_id
     */
    private void saveShare(List<PageData> list_share, String pro_id) throws Exception {
        if (list_share != null && list_share.size() > 0) {
            int i = 1;
            for (PageData pageData : list_share) {
                pageData.put("orderNum", i);
                pageData.put("propertyId", pro_id);
                pageData.put("id", UuidUtil.get32UUID());
                i++;
            }
            shareholdingChangeDao.saveAll(list_share);
        }
    }


    /**
     * 保存出资人情况
     *
     * @param list_con
     * @param pro_id
     */
    private void saveCon(List<PageData> list_con, String pro_id) throws Exception {
        if (list_con != null && list_con.size() > 0) {
            int i = 1;
            for (PageData pageData : list_con) {
                pageData.put("orderNum", i);
                pageData.put("proChagId", pro_id);
                pageData.put("id", UuidUtil.get32UUID());
                i++;
            }
            contributorChangeDao.saveAll(list_con);
        }
    }


    /**
     * 保存出资人情况
     *
     * @param list_con
     * @param pro_id
     * @param type     1 基础从表，2记录从表
     */
    private void saveCon(List<PageData> list_con, String pro_id, int type) throws Exception {
        if (type == 1) {
            contributorBasicsDao.del_parentId(pro_id);
        }
        if (list_con != null && list_con.size() > 0) {
            for (PageData pageData : list_con) {
                pageData.put("propertyId", pro_id);
            }
            if (type == 1) {
                contributorBasicsDao.saveAll(list_con);
            }
            if (type == 2) {
                contributorRecordDao.saveAll(list_con);
            }
        }
    }

    /**
     * 保存境外控股人
     *
     * @param list_share
     * @param pro_id     主表id
     * @param type       1 基础从表，2记录从表
     */
    private void saveShare(List<PageData> list_share, String pro_id, int type) throws Exception {
        if (type == 1) {
            shareholdingBasicsDao.del_parentId(pro_id);
        }
        if (list_share != null && list_share.size() > 0) {
            for (PageData pageData : list_share) {
                pageData.put("propertyId", pro_id);
            }
            if (type == 1) {
                shareholdingBasicsDao.saveAll(list_share);
            }
            if (type == 2) {
                shareholdingRecordDao.saveAll(list_share);
            }
        }
    }

    /**
     * 保存
     *
     * @param list    从表列表
     * @param prentId 主键id
     */
    private void savePartnerSituation(List<PageData> list, String prentId, int type) throws Exception {
        if (type == 1) {
            partnerSituationBascicsDao.delPrenteId(prentId);
        }
        if (list != null && list.size() > 0) {
            for (PageData pageData : list) {
                pageData.put("propertyId", prentId);
            }
            if (type == 1) {
                partnerSituationBascicsDao.saveAll(list);
            }
            if (type == 2) {
                partnerSituationRecordDao.saveAll(list);
            }
        }
    }

    /**
     * 保存合伙人从表
     *
     * @param list    从表列表
     * @param prentId 主键id
     */
    private void savePartnerOutbound(List<PageData> list, String prentId, int type) throws Exception {
        if (type == 1) {
            partnerOutboundBasicsDao.delPrenteId(prentId);
        }
        if (list != null && list.size() > 0) {
            for (PageData pageData : list) {
                pageData.put("propertyId", prentId);
            }
            if (type == 1) {
                partnerOutboundBasicsDao.saveAll(list);
            }
            if (type == 2) {
                partnerOutboundRecordDao.saveAll(list);
            }
        }
    }


    /**
     * 查询主表，从表数据
     *
     * @param pd
     * @return
     */
    public ObjResult findbyidAll(PageData pd) {
        String pro_id = pd.getString("id");
        ObjResult objResult;
        try {
            //主要行业
            PageData p = propertyChangeDao.findbyid(pro_id);
            for (int i = 1; i <=6; i++) {
                String v=p.getString("actualCapital"+i);
                if(Tools.isEmpty(v)|| "0".equals(v)){
                    p.put("actualCapital"+i,"0.00");
                }else{
                    BigDecimal b=new BigDecimal(v).setScale(2, RoundingMode.HALF_UP);
                    p.put("actualCapital"+i,b.toPlainString());
                }
            }
            p.put("netWorkingName", netWorkingName(p.getString("netWorking")));

            //变动原因
            if (Tools.notEmpty(p.getString("changeReason"))) {
                p.put("changeReasonNames", industryNames(p.getString("changeReason")));
                p.put("changeReason", Arrays.asList(p.getString("changeReason").split(",")));
            } else {
                p.put("changeReason", new ArrayList<>());
            }
            //出资人情况
            List<PageData> list_con = contributorChangeDao.find_parentId(pro_id);
            if (Tools.notEmpty(p.getString("nature"))) {
                if ("1".equals(p.getString("nature"))) {
                    List<PageData> list_share = shareholdingChangeDao.find_parentId(pro_id);
                    p.put("list_share", list_share);
                }
                if ("2".equals(p.getString("nature"))) {
                    List<PageData> list_PartnerSituation = partnerSituationChangeDao.find_parentId(pro_id);
                    p.put("listPartnerSituation", list_PartnerSituation);
                    List<PageData> list_PartnerOutbound = partnerOutboundChangeDao.find_parentId(pro_id);

                    List<String> parentId1 = new ArrayList<>();
                    parentId1.add("110");
                    PageData p_o1 = new PageData();
                    p_o1.put("parentId", parentId1);
                    List<Tree> l = baseInfoDao.findTree(p_o1);
                    for (PageData pageData : list_PartnerOutbound) {
                        String industry = pageData.getString("industry");
                        if (Tools.notEmpty(industry)) {
                            pageData.put("industryName", industryNames(industry, l));
                            pageData.put("industry", Arrays.asList(industry.split(",")));
                        }
                    }
                    p.put("listPartnerOutbound", list_PartnerOutbound);
                }
            }
            if (Tools.notEmpty(p.getString("majorIndustries"))) {
                p.put("majorIndustriesNames", industryNames(p.getString("majorIndustries")));
                p.put("majorIndustries", Arrays.asList(p.getString("majorIndustries").split(",")));
            } else {
                p.put("majorIndustriesNames", new ArrayList<>());
                p.put("majorIndustries", new ArrayList<>());
            }


            p.put("list_con", list_con);
            fileList(p);
            p.put("list_con", list_con);
            objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
        }
        return objResult;
    }

    private void fileList(PageData pd) throws Exception {
        List<PageData> l = fileDao.findParentId(pd.getString("id"));
        for (int i = 1; i <= 9; i++) {
            List<PageData> l2 = new ArrayList<>();
            for (PageData pageData : l) {
                if (pageData.getString("type").equals("f" + i)) {
                    pageData.put("itFileName", pageData.getString("fileName"));
                    pageData.put("viewFileName", pageData.getString("fileName"));
                    String fileName = pageData.getString("fileName");
                    //文件后缀
                    String fileTyle = fileName.substring(fileName.lastIndexOf("."));
                    if (!"pdf".equalsIgnoreCase(fileTyle)) {
                        BigDecimal bigDecimal = new BigDecimal(pageData.getString("fileSize"));
                        BigDecimal b = bigDecimal.divide(new BigDecimal("1048576"), 2, RoundingMode.HALF_UP);
                        if (b.floatValue() <= 20) {
                            pageData.put("isPrint", true);
                        } else {
                            pageData.put("isPrint", false);
                        }
                    } else {
                        pageData.put("isPrint", true);
                    }

                    if (Tools.notEmpty(fileName)) {
                        fileName = fileName.substring(19);
                        pageData.put("fileName", fileName);
                    }
                    l2.add(pageData);
                    break;
                }
            }
            pd.put("f" + i, l2);
        }
    }

    /**
     * 行业转换
     *
     * @return
     */
    private List<String> industryNames(String codes) throws Exception {
        List<String> l = Arrays.asList(codes.split(","));
        List<PageData> baseInfo = baseInfoDao.findbycodes(l);
        List l1 = new ArrayList();
        for (String code : l) {
            String s1 = "";
            for (PageData pageData : baseInfo) {
                if (pageData.getString("code").equals(code)) {
                    s1 = pageData.getString("name");
                    break;
                }
            }
            l1.add(s1);
        }
        return l1;
    }

    /**
     * 行业转换
     *
     * @return
     */
    private List<String> industryNames(String codes, List<Tree> list) throws Exception {
        String[] l = codes.split(",");
        List l1 = new ArrayList();
        for (String code : l) {
            String s1 = "";
            for (Tree pageData : list) {
                if (pageData.getCode().equals(code)) {
                    s1 = pageData.getName();
                    break;
                }
            }
            l1.add(s1);
        }
        return l1;
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    public ObjResult del_ids(List<String> id) {
        ObjResult objResult;
        try {
            propertyChangeDao.del_ids(id);
            for (String s : id) {
                formWorkflowService.deleteProcessInstance(s);
            }

            objResult = new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
        }
        return objResult;
    }

    /**
     * 查询列表
     *
     * @return
     */
    public ListResult listPage(PageData pd) {
        ListResult listResult;
        try {
            if(pd.get("search")!=null){ //新增注册日期的查询
                List<HashMap<String,Object>> searchEntityList=(List<HashMap<String,Object>>)pd.get("search");
                if(searchEntityList.size()>0){
                    HashMap<String,Object>  entity=searchEntityList.get(0);
                    if(entity.get("field")!=null&&entity.get("field").equals("year")&&entity.get("value")!=null){
                        List<String> stringList=(List<String>)entity.get("value");
                        if(stringList!=null&&stringList.size()>1){
                            if(com.plian.Tools.StringUtil.isNotBlank(stringList.get(0))){
                                pd.put("startTime",stringList.get(0));
                            }
                            if(com.plian.Tools.StringUtil.isNotBlank(stringList.get(1))){
                                pd.put("endTime",stringList.get(1));
                            }
                        }
                    }
                }
                pd.put("","");
            }
            pd.put("fillOrgId", TokenUtil.getTokenOrgId());
            Page page = new Page(true, pd);
            List<PageData> list = propertyChangeDao.listPage(page);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            listResult.setTotal(page.getTotal());
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            listResult = new ListResult(CommonCode.ERROR);
        }
        return listResult;
    }


    /**
     * 变动处理
     */
    private void ChagWith(String id) throws Exception {
        //得到产权变动信息
        PageData change = propertyChangeDao.findbyid(id);
        change.remove("formType");
        change.remove("createTime");
        change.remove("updateTime");
        change.remove("createUser");
        change.remove("updateUser");
        change.remove("fillOrgId");
        change.remove("status");
        change.remove("id");


        //拿到对应变动记录表数据
        PageData p = propertyRecordDao.findbyid(change.getString("proId"));

        //初始id
        String initial_id = p.getString("initialId");
        PageData basics = propertyBasicsDao.findbyid(initial_id);
        String oldParentId = basics.getString("parentId");
        PageData p2=new PageData();
        p2.putAll(basics);
        Date now = new Date();

        //记录表id
        String recordId = UuidUtil.get32UUID();
        //修改标准表
        basics.put("updateTime", now);
        basics.putAll(change);
        propertyBasicsDao.edit(basics);
        PropertyCache.update(basics.getString("id"));
        if (!oldParentId.equals(basics.getString("parentId"))){
            propertyBasicsService.changeNewPropertyCode(initial_id, basics.getString("parentId"));
        }
        propertyBasicsService.changeChildPrivateMix(initial_id,
                propertyBasicsService.checkActualCapital5(basics.getString("actualCapital5")) ? 1 : 0);

        //记录表
        PageData record = new PageData();
        record.putAll(basics);
        record.put("id", recordId);
        record.put("updateTime", now);
        record.put("changeId", change.getString("id"));
        record.put("initialId", initial_id);
        propertyRecordDao.save(record);

        List<PageData> fileList = fileDao.findParentId(id);
        List<HashMap> recordFileList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(fileList)){
            for (PageData file : fileList){
                HashMap recordFile = new HashMap();
                recordFile.putAll(file);
                recordFile.put("id", UuidUtil.get32UUID());
                recordFile.put("parentId", recordId);
                recordFileList.add(recordFile);
            }
            fileDao.saveAll(recordFileList);
        }

//        //保存企业章程 TODO DEL
//        saveAssociation(change,recordId);

        //出资人情况
        List<PageData> list_con = contributorChangeDao.find_parentId(id);
        //基础表
        saveCon(list_con, initial_id, 1);
        //记录表
        saveCon(list_con, recordId, 2);


        String nature = change.getString("nature");
        if ("1".equals(nature)) {
            List<PageData> list_share = shareholdingChangeDao.find_parentId(id);
            //基础表
            saveShare(list_share, initial_id, 1);
            //记录表
            saveShare(list_share, recordId, 2);
        }
        if ("2".equals(nature)) {
            List<PageData> list_PartnerSituation = partnerSituationChangeDao.find_parentId(id);
            List<PageData> list_PartnerOutbound = partnerOutboundChangeDao.find_parentId(id);
            //基础表
            savePartnerSituation(list_PartnerSituation, initial_id, 1);
            savePartnerSituation(list_PartnerSituation, recordId, 2);
            //记录表
            savePartnerOutbound(list_PartnerOutbound, initial_id, 1);
            savePartnerOutbound(list_PartnerOutbound, recordId, 2);
        }

        String orgId = change.getString("orgId");
        if (Tools.notEmpty(orgId)) {
            PageData org = orgzationDao.findbyid(orgId);
            String changeOrgName = change.getString("orgName");
            if (!org.getString("name").equals(changeOrgName)) {
                PageData orgrecord = new PageData();
                //保存变更前数据
                orgrecord.putAll(org);
                orgrecord.put("orgId", org.getString(id));
                orgrecord.put("id", UuidUtil.get32UUID());
                orgrecord.put("updateTime", new Date());
                orgzationDao.orgrecord(orgrecord);
                //更新企业
                org.put("name", changeOrgName);
                orgzationDao.edit(org);
            }
        }

        if ("2".equals(nature)) {
            //合伙企业特殊处理
            return;
        }

        boolean flag = "001001".equals(p2.getString("orgGradation"))
                || "001001".equals(basics.getString("orgGradation"));
        //如果为一级企业，批量修改下级所有企业级次、国有出资人名称
        List<PageData> listAll = propertyBasicsDao.listInfo(null);
        //变更后
        String orgGradation = basics.getString("orgGradation");
        orgGradation = orgGradation.substring(orgGradation.length() - 3);
        int i = Integer.valueOf(orgGradation);
        //下级所有企业
        List<PageData> listChlid = listChlid(basics.getString("id"), listAll, null, basics.getString("stateFundedName"), i, flag, now);

        if (CollectionUtil.isEmpty(listChlid)){
            return;
        }
        propertyBasicsDao.editAll(listChlid);
        PropertyCache.updateBatch(propertyBasicsService.list(new LambdaQueryWrapper<PropertyBasics>().in(PropertyBasics::getId, listChlid.stream()
                .map(childPropertyBasic -> p.getString("id")).collect(Collectors.toList()))));
        PropertyCache.update(basics.getString("id"));

        List<PageData> allRecordList = propertyRecordDao.allInfoList();
        Map<String, List<PageData>> recordMap = allRecordList.stream().collect(Collectors.groupingBy(recordPd -> recordPd.getString("initialId")));

        List<String> listIds=listChlid.stream().map(pageData -> pageData.getString("id")).collect(Collectors.toList());

        List<PageData> listRecord=new ArrayList<>();
        //需要操作的子表
        List<PageData> l1 = contributorBasicsDao.findByParentIds(listIds);
        List<PageData> l2 = shareholdingBasicsDao.findByParentIds(listIds);
        List<PageData> l3 = partnerSituationBascicsDao.findByParentIds(listIds);
        List<PageData> l4 = partnerOutboundBasicsDao.findByParentIds(listIds);

        //批量添加记录表
        for (PageData pageData : listChlid) {
            String rId=UuidUtil.get32UUID();
            PageData r=new PageData();
            r.putAll(pageData);
            r.put("id", rId);
            r.put("updateTime", now);
            r.put("status","3");
            r.put("initialId", pageData.get("id"));
            listRecord.add(r);

            if (recordMap.containsKey(pageData.getString("id"))){
                List<PageData> recordList = recordMap.get(pageData.getString("id"));
                if (recordList.size() > 1){
                    recordList.sort((a1, a2) -> {
                        try {
                            return DateUtil.parse(a2.getString("updateTime"), DateUtil.PATTERN_DATETIME)
                                    .compareTo(DateUtil.parse(a1.getString("updateTime"), DateUtil.PATTERN_DATETIME));
                        } catch (Exception e) {
                            log.error(ExceptionUtils.getFullStackTrace(e));
                        }
                        return 1;
                    });
                }

                PageData lastRecord = recordList.get(0);
                List<PageData> lastRecordFileList = fileDao.findParentId(lastRecord.getString("id"));
                if (CollectionUtil.isNotEmpty(lastRecordFileList)){
                    List<HashMap> childRecordFileList = new ArrayList<>();
                    for (PageData file : lastRecordFileList){
                        HashMap recordFile = new HashMap();
                        recordFile.putAll(file);
                        recordFile.put("id", UuidUtil.get32UUID());
                        recordFile.put("parentId", rId);
                        childRecordFileList.add(recordFile);
                    }
                    fileDao.saveAll(childRecordFileList);
                }
            }

            for (PageData data : l1) {
                if(pageData.getString("id").equals(data.getString("propertyId"))){
                    data.put("propertyId",rId);
                    data.put("id",UuidUtil.get32UUID());
                }
            }
            for (PageData data : l2) {
                if(pageData.getString("id").equals(data.getString("propertyId"))){
                    data.put("propertyId",rId);
                    data.put("id",UuidUtil.get32UUID());
                }
            }
            for (PageData data : l3) {
                if(pageData.getString("id").equals(data.getString("propertyId"))){
                    data.put("propertyId",rId);
                    data.put("id",UuidUtil.get32UUID());
                }
            }
            for (PageData data : l4) {
                if(pageData.getString("id").equals(data.getString("propertyId"))){
                    data.put("propertyId",rId);
                    data.put("id",UuidUtil.get32UUID());
                }
            }
        }
        propertyRecordDao.saveAll(listRecord);
        if(l1!=null && l1.size()>0){
            contributorRecordDao.saveAll(l1);
        }
        if(l2!=null && l2.size()>0) {
            shareholdingRecordDao.saveAll(l2);
        }
        if(l3!=null && l3.size()>0) {
            partnerSituationRecordDao.saveAll(l3);
        }
        if(l4!=null && l4.size()>0) {
            partnerOutboundRecordDao.saveAll(l4);
        }

    }

//    /** TODO DEL
//     * @Description: //TODO 保存企业章程
//     * @Author: Take-off
//     * @Date: 2:54 PM 2023/4/7
//     * @Param: [change, recordId]
//     * @return: void
//     **/
//    private void saveAssociation(PageData change,String recordId){
//        try {
//            List<PageData> changeFiles=  fileDao.findParentId(change.getString("id"));
//            String proId = change.getString("proId");
//            String orgId = change.getString("orgId");
//            List<PageData> lastRecordFiles=  fileDao.findParentId(proId);
//            String oldFileName = "";
//            if (CollectionUtil.isNotEmpty(lastRecordFiles)){
//                Optional<PageData> recordFile = lastRecordFiles.stream().filter(m -> com.plian.Tools.StringUtil.isNotBlank(m.getString("type")) && "f5".equals(m.getString("type"))).findFirst();
//                if (recordFile.isPresent()) {
//                    PageData file = recordFile.get();
//                    oldFileName = file.getString("fileName");
//                }
//            }
//            if (CollectionUtil.isNotEmpty(changeFiles)){
//                Optional<PageData> changeFile = changeFiles.stream().filter(m -> com.plian.Tools.StringUtil.isNotBlank(m.getString("type")) && "f5".equals(m.getString("type"))).findFirst();
//                if (changeFile.isPresent()) {
//                    PageData file = changeFile.get();
//                    String fileName = file.getString("fileName");
//                    if (!fileName.contains(oldFileName)){
//                        EnterpriseAssociation enterpriseAssociation = new EnterpriseAssociation();
//                        enterpriseAssociation.setFillingYear(DateUtil.format(new Date(),DateUtil.PATTERN_YEAR));
//                        enterpriseAssociation.setFillingUnitId(orgId);
//                        enterpriseAssociation.setFillingTime(new Date());
//                        enterpriseAssociation.setFileName(fileName.substring(19));
//                        enterpriseAssociation.setBelongUnitId(orgId);
//                        enterpriseAssociation.setEffectTime(new Date());
//                        enterpriseAssociation.setFileStatus(1);
//                        enterpriseAssociation.setAssociationStatus(1);
//                        enterpriseAssociation.setProId(recordId);
//                        enterpriseAssociation.setOrgId(orgId);
//                        HashMap fileMap = new HashMap(file);
//                        fileMap.remove("id");
//                        fileMap.remove("parentId");
//                        fileMap.put("itFileName",fileMap.get("fileName"));
//                        enterpriseAssociation.setDocList(Collections.singletonList(fileMap));
//                        //查询老的
//                        List<EnterpriseAssociation> oldAssociations = changeAssociationService.list(new LambdaQueryWrapper<EnterpriseAssociation>().eq(EnterpriseAssociation::getProId, proId));
//                        if (CollectionUtil.isNotEmpty(oldAssociations)){
//                            EnterpriseAssociation oldAssociation = oldAssociations.get(0);
//                            if (Optional.ofNullable(oldAssociation.getInitialId()).isPresent()){
//                                enterpriseAssociation.setInitialId(oldAssociation.getInitialId());
//                            }else {
//                                enterpriseAssociation.setInitialId(oldAssociation.getInitialId());
//                            }
//                            enterpriseAssociation.setVersion(oldAssociation.getVersion());
//                            enterpriseAssociation.setLastVersionId(oldAssociation.getId());
//                        }
//                        changeAssociationService.submit(enterpriseAssociation);
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 处理子数据
     *
     * @param pid             父id
     * @param listAll         产权所有集合
     * @param stateFundedName 国家出资企业
     * @param grade 国家出资企业
     * @return  下级所有企业
     */
    public List<PageData> listChlid(String pid, List<PageData> listAll, List<PageData> list, String stateFundedName, int grade, boolean flag, Date now) {
        List<PageData> varList = new ArrayList<>();
        if (list == null) {
            list = new ArrayList<>();
        }
        grade+=1;
        String orgGradation="";
        if (grade < 10) {
            orgGradation = "00100" + grade;
        } else if (grade < 100) {
            orgGradation = "0010" + grade;
        }
        for (PageData pageData : listAll) {
            //子集
            List<PageData> l = new ArrayList<>();
            //添加子集
            if (pageData.getString("parentId").equals(pid)) {
                l.add(pageData);
            }
            //递归添加子集
            if (l != null && l.size() > 0) {
                for (PageData data : l) {
//                    if (flag){
                        data.put("stateFundedName", stateFundedName);
//                    }
                    data.put("orgGradation", orgGradation);
                    data.put("updateTime", now);
                    varList.add(data);
                    listChlid(data.getString("id"), listAll, list, stateFundedName, grade, flag, now);
                }
            }
        }
        list.addAll(varList);
        return list;
    }


    /**
     * 提交单据
     *
     * @param formId 单据id
     */
    public HashMap<String, Object> commit(String formId){
        //拿到变动信息
        List<PageData> l = null;
        try {
            PageData p = propertyChangeDao.findbyid(formId);
            l = propertyChangeDao.findByWayName(p);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException("获取单据信息失败");
        }
        if (l != null && l.size() > 0) {
            ObjResult objResult = new ObjResult(CommonCode.EXIST);
            objResult.setMessage("该单位已存在");
            throw new MyRuntimeException(objResult);
        }
        PageData pageData = new PageData();
        pageData.put("status", String.valueOf(FLOW));
        ArrayList<String> ids = new ArrayList<>();
        ids.add(formId);
        pageData.put("id", ids);
        try {
            propertyChangeDao.refer(pageData);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException("提交失败");
        }
        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String, Object>();
    }

    /**
     * 退回单据
     *
     * @param formId 单据id
     */
    public Boolean reject(String formId, int formState, String comment){
        PageData pageData = new PageData();
        pageData.put("status", String.valueOf(formState));
        pageData.put("id", Collections.singletonList(formId));
        try {
            propertyChangeDao.refer(pageData);
            saveMessage(formId, false, comment);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException("回退失败");
        }
        return true;
    }

    /**
     * 单据完成后
     *
     * @param formId
     */
    public Boolean finish(String formId) {
        try {
            PageData pageData = new PageData();
            pageData.put("status", String.valueOf(FINISH));
            pageData.put("id", Collections.singletonList(formId));
            pageData.put("approvalDate", new Date());
            propertyChangeDao.refer(pageData);
            saveMessage(formId, true, "审批通过");
            propertyChangeHelper.changeWith(formId);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult("单据流转完成时修改单据状态失败！"));
        }
        return true;
    }

    private void saveMessage(String formId, boolean approval, String comment) throws Exception{
        PageData pd = propertyChangeDao.findbyid(formId);
        String dataSource = pd.getString("dataSource");
        String dataSourceId = pd.getString("dataSourceId");
        if (StringUtils.isNotBlank(dataSource)
                && StringUtils.isNotBlank(dataSourceId)
                && !dataSource.equals(YthConstant.DATA_NINGBO)){
            ApprovalMessage approvalMessage = new ApprovalMessage();
            approvalMessage.setDataSourceId(dataSourceId);
            approvalMessage.setType(PROPERTY_CHANGE);
            approvalMessage.setOpinion(comment);
            approvalMessage.setIsApprove(approval ? 2 : 1);
            approvalMessage.setIsSend(1);
            approvalMessage.setDataSourceType(KT_TYPE);
            approvalMessageService.save(approvalMessage);
        }
    }

    /**
     * @param formIds 单据ids
     */
    public List<PageData> findByIds(List<String> formIds) {
        try {
            PageData pageData = new PageData();
            pageData.put("id", formIds);
            return propertyChangeDao.findByIds(pageData);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException("根据单据id列表查询报表失败！");
        }
    }

    @Override
    public List<Integer> getFormType() {
        return Collections.singletonList(PM_PROPERTYCHANGE_FORM);
    }

    public void goBackToStash(String formId) {
        try {
            PageData pageData = new PageData();
            pageData.put("status", String.valueOf(UNREVIEWED));
            pageData.put("id", Collections.singletonList(formId));
            propertyChangeDao.refer(pageData);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
    }


    public ListResult<PageData> reportList(PageData pd, boolean isPage) {
        Page page = new Page(isPage, pd);
        try {
            //变动原因
            List<String> parentId = new ArrayList<>();
            parentId.add("084");
            PageData p_o = new PageData();
            p_o.put("parentId", parentId);
            List<Tree> trees = baseInfoDao.findTree(p_o);
            List<PageData> list = propertyChangeDao.reportListPage(page);
            for (PageData pageData : list) {
                //变动原因
                if (Tools.notEmpty(pageData.getString("changeReason"))) {
                    String[] changeReasons = pageData.getString("changeReason").split(",");
                    List<String> s = new ArrayList<>();
                    for (String changeReason : changeReasons) {
                        for (Tree tree : trees) {
                            if (changeReason.equals(tree.getCode())) {
                                if (tree.getCode().equals(changeReason)) {
                                    s.add(tree.getName());
                                }
                            }
                        }
                    }
                    pageData.put("changeReason", String.join(" | ", s));
                }
                String nature = pageData.getString("nature");
                if (Tools.notEmpty(nature)) {
                    if ("0".equals(nature)) {
                        pageData.put("nature", "境内");
                    } else if ("1".equals(nature)) {
                        pageData.put("nature", "境外");
                    }
                } else if ("2".equals(nature)) {
                    pageData.put("nature", "合伙人");
                } else {
                    pageData.put("nature", "");
                }
                String changeNature = pageData.getString("changeNature");
                if (Tools.notEmpty(changeNature)) {
                    if ("0".equals(changeNature)) {
                        pageData.put("changeNature", "境内");
                    } else if ("1".equals(nature)) {
                        pageData.put("changeNature", "境外");
                    }
                } else if ("2".equals(nature)) {
                    pageData.put("changeNature", "合伙人");
                } else {
                    pageData.put("changeNature", "");
                }
            }
            ListResult listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            listResult.setTotal(page.getTotal());
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    public R<ReportReturnVO> changeReasonCount(PropertyChangeDTO propertyChangeDTO){
        List<EconomicBehaviorCountVO> results = initChangeReasonCount(propertyChangeDTO);
        try {
            List<EconomicBehaviorCountVO> economicBehaviorCountVOS = new ArrayList<>();
            if (propertyChangeDTO.getIsChangeReason()){
                economicBehaviorCountVOS.addAll(propertyChangeDao.changeReasonCount(propertyChangeDTO));
            }

            if (propertyChangeDTO.getIsSituation()){
                economicBehaviorCountVOS.addAll(propertyDao.situationCount(propertyChangeDTO));
            }

            if (propertyChangeDTO.getIsOutReason()){
                economicBehaviorCountVOS.addAll(propertyOutDao.outReasonCount(propertyChangeDTO));
            }

            if (CollectionUtil.isNotEmpty(economicBehaviorCountVOS)){
                Map<String, List<EconomicBehaviorCountVO>> map = economicBehaviorCountVOS.stream()
                        .collect(Collectors.groupingBy(EconomicBehaviorCountVO::getEconomicBehavior));
                results.stream().forEach(result -> {
                    if (map.containsKey(result.getEconomicBehavior())){
                        List<EconomicBehaviorCountVO> countVOS = map.get(result.getEconomicBehavior());
                        result.setCount(countVOS.size());
                        result.getOrgList().addAll(countVOS);
                    }
                });
            }

        }catch (Exception e){
            log.error("PropertyChangeService ------->changeReasonCount：" + e);
            return new R(CustomCode.builder().message("获取统计结果失败").code(1999).success(false).build());
        }
        ReportReturnVO reportReturnVO = new ReportReturnVO();

        ReportVO reportVO = new ReportVO();

        reportVO
                .addHeader(HeaderVO.builder().key("changeReasonName").title("经济行为").build())
                .addHeader(HeaderVO.builder().key("count").title("办理次数").build());
        reportVO.setData(results);
        reportReturnVO.setGrids(reportVO);
        R<ReportReturnVO> obj =  new R<>(CommonCode.SUCCESS);
        obj.setPageData(reportReturnVO);
        return obj;
    }

    /**
     * 导出经济行为分析
     * @param propertyChangeDTO
     * @param request
     * @param response
     */
    public void exportExcelofEconomicBehavior(PropertyChangeDTO propertyChangeDTO,HttpServletRequest request, HttpServletResponse response)  {
        R<ReportReturnVO> result=changeReasonCount(propertyChangeDTO);
        ExcelExportUtil excel=new ExcelExportUtil();
        excel.setTitle("经济行为分析");
        List<EconomicBehaviorCountVO> reportList=result.getPageData().getGrids().getData();
        List<Map> list=new ArrayList<>();
        for(EconomicBehaviorCountVO r:reportList){
            Map m=new HashMap();
            m.put("economicBehaviorName",r.getEconomicBehaviorName());
            m.put("count",r.getCount());
            list.add(m);
        }
        excel.setData(list);
        try {
            String separator = File.separator;
            String exlPath = separator + "exceldemo" + separator + "economicBahavior.xlsx";
            InputStream inputStream = this.getClass().getResourceAsStream(exlPath);
            String fileName = URLEncoder.encode("经济行为分析", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 设置响应头和客户端保存文件名
            response.setCharacterEncoding("utf-8");
            OutputStream outputStream = response.getOutputStream();// 取得输出流
            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(list, fillConfig, writeSheet);
            excelWriter.finish();
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 导出经济行为分析查看详情
     * @param propertyChangeDTO
     * @param request
     * @param response
     */
    public void exportExcelofEconomicBehaviorDetail(PropertyChangeDTO propertyChangeDTO,HttpServletRequest request, HttpServletResponse response)  {
        R<ReportReturnVO> result=changeReasonCount(propertyChangeDTO);
        ExcelExportUtil excel=new ExcelExportUtil();
        excel.setTitle("经济行为分析详情");
        List<EconomicBehaviorCountVO> reportList=result.getPageData().getGrids().getData();
        List<Map> list=new ArrayList<>();
        String economicBehavior=propertyChangeDTO.getEconomicBehavior();
        String[] headerList=new String[]{"序号","企业名称"};
        String[] headerKey=new String[]{"orderNum","economicBehaviorName"};
        for(EconomicBehaviorCountVO r:reportList){
            if(economicBehavior.equals(r.getEconomicBehavior())){
                List<EconomicBehaviorCountVO> orgList=r.getOrgList();
                for(int i=0;i<orgList.size();i++){
                    Map m=new HashMap();
                    m.put("orderNum",i+1);
                    m.put("economicBehaviorName",orgList.get(i).getOrgName());
                    list.add(m);
                }
            }

        }
        excel.setData(list);
        excel.setHeardKey(headerKey);
        excel.setHeardList(headerList);
        excel.setFileName("经济行为分析详情");
        try {
            excel.exportExport(request,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化返回类别
     * @param propertyChangeDTO
     * @return
     */
    public List<EconomicBehaviorCountVO> initChangeReasonCount(PropertyChangeDTO propertyChangeDTO){
        List<String> economicBehaviors = propertyChangeDTO.getEconomicBehaviors();

        List<String> allParentCode = new ArrayList<>();
        allParentCode.add(ValueSetConstant.SITUATION);
        allParentCode.add(ValueSetConstant.CHANGE_REASON);
        allParentCode.add(ValueSetConstant.OUT_REASON);
        propertyChangeDTO.setIsChangeReason(true);
        propertyChangeDTO.setIsOutReason(true);
        propertyChangeDTO.setIsSituation(true);
        if(CollectionUtil.isNotEmpty(economicBehaviors)){
            if (!economicBehaviors.contains(ValueSetConstant.CHANGE_REASON)){
                allParentCode.remove(ValueSetConstant.CHANGE_REASON);
                propertyChangeDTO.setIsChangeReason(false);
            }

            if (!economicBehaviors.contains(ValueSetConstant.OUT_REASON)){
                allParentCode.remove(ValueSetConstant.OUT_REASON);
                propertyChangeDTO.setIsOutReason(false);
            }

            if (!economicBehaviors.contains(ValueSetConstant.SITUATION)){
                allParentCode.remove(ValueSetConstant.SITUATION);
                propertyChangeDTO.setIsSituation(false);
            }
        }

        List<EconomicBehaviorCountVO> initList = new ArrayList<>();
        for (String parentCode : allParentCode){
            Map<String, String> map = baseInfoService.getChildMap(parentCode);
            Set<String> codes = map.keySet();
            List<String> childCodes = codes.stream().filter(code ->{
                for (String str : codes){
                    if (str.length() > str.length() && str.startsWith(code)){
                        return false;
                    }
                }
                return true;
            }).collect(Collectors.toList());

            String str = "";
            int type = 0;
            if(ValueSetConstant.SITUATION.equals(parentCode)){
                str = "占有-";
                type = 1;
            }else if (ValueSetConstant.CHANGE_REASON.equals(parentCode)){
                str = "变动-";
                type = 2;
            }else if(ValueSetConstant.OUT_REASON.equals(parentCode)){
                str = "注销-";
                type = 3;
            }

            for (String childCode : childCodes){
                initList.add(EconomicBehaviorCountVO.builder()
                        .orgList(new ArrayList<>()).type(type)
                        .economicBehavior(childCode).economicBehaviorName(str + map.get(childCode))
                        .count(0).build());
            }
        }

        initList = initList.stream().sorted(Comparator
                .comparing(EconomicBehaviorCountVO::getEconomicBehavior)).collect(Collectors.toList());

        return initList;

    }
}
